<template>
  <div class="main-pointGroupSearch">
    <div class="layui-tab layui-tab-brief" lay-filter="test-handle">
      <ul class="layui-tab-title">
        <li class="layui-this" lay-id="search">查询</li>
        <li lay-id="result">显示结果</li>
      </ul>
      <div class="layui-tab-content">
        <div class="layui-tab-item layui-show">

          <div class="layui-col-md6 listPanel">
            <div class="layui-form-item listTopPanel">
              <label class="layui-form-label">类型:</label>
              <div class="layui-input-block">
                <select id="zuheDianSearch_layerSelect" v-model="type" style="width:200px; height:30px; color:black;">
                  <option v-for="(item ,index) in typeOptions" :key="index" style="color:#000"
                          :value="item.pipelineType">{{ item.type }}
                  </option>
                </select>
              </div>
            </div>
            <div class="layui-form-item listBottomPanel">

              <ul id="zuheSelect1_point" style="list-style:none; padding: 0; margin: 0; width: 120px;">
                <li v-for="(item,index) in list" :key="item.name" :class="{active:index===listSelected}" :t="item.type"
                    @click="handleListClick(item,index)">
                  {{ item.name }}
                </li>
              </ul>
              <ul id="zuheSelect2_point" style="list-style:none; padding: 0; margin: 0; width: 100px;">
                <li v-for="(item,index) in list2" :key="item.name" :class="{active:index===listSelected2}"
                    @click="handleListClick2(item, index)"
                    :t="item.type">{{ item.name }}
                </li>

              </ul>
              <ul id="zuheSelect3_point"
                  style="list-style:none; padding: 0; margin: 0; overflow:overlay; width: 200px; max-height: 350px;">
                <li v-for="(item,index) in list3" :key="item.name" :t="item.name"
                    :class="{active:index===listSelected3}" @click="handleListClick3(item, index)">
                  {{ item.name }}
                </li>
              </ul>
              <div class="buttonGroup">
                <!-- <select id="zuheSelect4" style="width:100px; height:30px; color:black;">
                    <option style="color:#000" value="">或者</option>
                    <option style="color:#000" value="">并且</option>
                </select> -->
                <button id="toOr_point" @click="handleToOrClick" style="color: #000;">或者</button>
                <button id="toAnd_point" @click="handleToAndClick" style="color: #000;">并且</button>
                <button id="toLeft_point" @click="handleToLeftClick" style="color: #000;"> (</button>
                <button id="toRight_point" @click="handleToRightClick" style="color: #000;"> )</button>
                <button id="toText" @click="handleToTextClick" style="color: #000;"> -></button>
                <button id="clear-text-info_point" @click="handleClearClick" style="color: #000;">清空</button>
                <button id="toSearch_point" @click="handleToSearchClick" style="color: #000;">查询</button>
              </div>

            </div>
          </div>
          <textarea class="sqlPanel" id="text-info_point"
          ></textarea>

        </div>
        <div class="layui-tab-item">
          <table
              id="table"
              data-toggle="table"
              data-height="550"
              data-width="430"
              data-search="true"
              data-pagination="true"
              style="overflow: hidden;text-overflow: ellipsis;white-space: nowrap; color:#fff;"
          >
            <thead id="thead" style="color:#fff;">

            </thead>
          </table>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import layersMap from "@/components/js/layerMap";
import fetchData from "@/components/js/fetchData";
import clearWindow from "@/components/js/clearWindow";
import highLightColor from "@/components/js/highColor";

let $table = null
// eslint-disable-next-line no-unused-vars
let from
export default {
  name: "pointGroupSearch",
  components: {},
  data() {
    return {
      type: '',
      typeOptions: [],
      list: [
        {type: 'string', name: '起点点号'},
        {type: 'string', name: '终点点号'},
        {type: 'number', name: '起点埋深'},
        {type: 'number', name: '终点埋深'},
        {type: 'number', name: '起点高程'},
        {type: 'number', name: '终点高程'},

        {type: 'string', name: '埋设方式'},
        {type: 'number', name: '管径'},

        {type: 'string', name: '材质'},
        {type: 'string', name: '所在道路'},
      ],
      listSelected: undefined,
      list2: [],
      listSelected2: undefined,
      list3: [],
      listSelected3: undefined,
    };
  },
  mounted() {
    layersMap.forEach(layer => {
      if (layer.pipelineType.endsWith('POINT')) {
        this.typeOptions.push({
          pipelineType: layer.pipelineType,
          type: layer.type
        })
      }
    })
    this.type = this.typeOptions[0].pipelineType
    $table && $table.bootstrapTable('destroy')
    $table = null;
    clearWindow()
  },
  methods: {
    async handleListClick(item, index) {
      this.listSelected = index
      let t = item.type
      let text = item.name
      if (t === 'string') {
        this.list2 = [
          {
            type: '==',
            name: '等于',
          }
        ]
      } else if (t === 'number') {
        this.list2 = [
          {
            type: '>',
            name: '大于'
          },
          {
            type: '<',
            name: '小于'
          },
          {
            type: '==',
            name: '等于'
          },
          {
            type: '>=',
            name: '大于等于'
          },
          {
            type: '<=',
            name: '小于等于'
          },
        ]
      }
      this.listSelected2 = 0
      let layer = layersMap.find(l => l.pipelineType == $('#zuheDianSearch_layerSelect').val())
      const res = await fetchData(layer.url)
      let list3 = []
      res.features.forEach((fea, index) => {
        let findIndex = list3.findIndex(item => {
          return item.name === fea.properties['' + text]
        })
        if (findIndex < 0) {
          list3.push({
            type: fea.properties['' + text],
            class: index === 0,
            name: fea.properties['' + text]
          })
        }

      })
      this.list3 = list3
      this.listSelected3 = 0
    },
    handleListClick2(item, index) {
      this.listSelected2 = index
    },
    handleListClick3(item, index) {
      this.listSelected3 = index
    },
    handleToOrClick() {
      $("#text-info_point").text($("#text-info_point").val() + ' or ')
    },
    handleToAndClick() {
      $("#text-info_point").text($("#text-info_point").val() + ' and ')
    },
    handleToLeftClick() {
      $("#text-info_point").text($("#text-info_point").val() + ' ( ')
    },
    handleToRightClick() {
      $("#text-info_point").text($("#text-info_point").val() + ' ) ')
    },
    handleToTextClick() {
      let select1 = $('#zuheSelect1_point li.active').text().trim()
      let select2 = $('#zuheSelect2_point li.active').attr('t').trim()
      let select3 = $('#zuheSelect3_point li.active').attr('t').trim()
      $("#text-info_point").text($("#text-info_point").val() + '"' + select1 + '"' + select2 + '"' + select3 + '"')
    },
    handleClearClick() {
      $("#text-info_point").text('')
    },
    async handleToSearchClick() {
      let val = $("#text-info_point").val()
      let fields = ['物探点号', '地面高程', '井深', '特征', '附属物']
      fields.forEach(field => {
        val = val.replace(new RegExp(`"${field}"`, 'g'), `fea.properties['${field}']`)
      })
      val = val.replace(/and/g, '&&')
      val = val.replace(/or/g, '||')
      let layer = layersMap.find(l => l.pipelineType == this.type)
      const res = await fetchData(layer.url)
      let properties = []
      let isError = false
      res.features.forEach(fea => {
        try {
          eval(val)
          if (eval(val)) {
            properties.push({...fea.properties,})
          }
        } catch (error) {
          isError = true
          // layui.layer.alert('表达式错误！')
          return;
        }
      })
      if (isError) {
        this.$message.warning('表达式错误！')
        return
      }

      if (properties.length == 0) {
        this.$message.warning('没有查询到符合条件的结果！')
        // layui.layer.alert('没有查询到符合条件的结果！')
        return;
      }
      this.refreshTable(properties, this)
      layui.element.tabChange('test-handle', 'result'); // 切换到：标签3
    },
    refreshTable(tableArr, that) {
      $table = $('#table');
      let thead = `<tr>`
      Object.keys(tableArr[0]).forEach(key => {
        thead += `<th data-field="${key}">${key}</th>`
      })
      thead += `</tr>`
      $table.bootstrapTable('destroy')
      $('#thead').html(thead)
      $table.bootstrapTable({
        data: tableArr,
        // eslint-disable-next-line no-unused-vars
        onClickRow: function (row, $element) {
          that.highLight(row)
        }
      })
      $table.bootstrapTable('refresh')
    },
    async highLight(row) {
      let name = row['物探点号']
      window.viewer.scene.primitives._primitives.forEach(tileset => {
        if (tileset instanceof Cesium.Cesium3DTileset) {
          tileset.style = new Cesium.Cesium3DTileStyle({
            color: {
              conditions: [
                ["${name} === '" + name + "'", 'color("red", 1)'.replace('red', highLightColor)],
                ['true', 'color("white",1.0)']
              ]
            },
          });
        }
      })
      let layer = layersMap.find(l => l.pipelineType === row['管线类型'])
      const res = await fetchData(layer.url)
      const feature = res.features.find(fea => fea.properties['物探点号'] === row['物探点号'])
      var highLightLayer = window.viewer.dataSources.getByName('highLightLayer')[0]
      if (!highLightLayer) {
        highLightLayer = new Cesium.CustomDataSource('highLightLayer')
        window.viewer.dataSources.add(highLightLayer)
      }
      // 绘制
      highLightLayer.entities.removeAll()
      highLightLayer.entities.add({
        name: "point",
        // position: Cesium.Cartesian3.fromDegreesArrayHeights(feature.geometry.coordinates),
        position: Cesium.Cartesian3.fromDegrees(feature.geometry.coordinates[0], feature.geometry.coordinates[1], feature.geometry.coordinates[2]),
        point: {
          color: new Cesium.Color.fromCssColorString("#3388ff"),
          pixelSize: 15,
          outlineColor: new Cesium.Color.fromCssColorString("#ffffff"),
          outlineWidth: 2,
          // heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,     //贴地
          // scaleByDistance: new Cesium.NearFarScalar(1000, 1, 1000000, 0.1),
          disableDepthTestDistance: Number.POSITIVE_INFINITY //不被遮挡
        },
      })
      window.viewer.flyTo(highLightLayer, {
        offset: new Cesium.HeadingPitchRange(0.0, -3.1415926 / 2.0, 70.0),
      })
    },
    clearDraw() {
      console.log('---zuheDianSearchClazz.clearDraw()')
      window.viewer.dadi.draw.clearDraw();
      from = null;
      let highLightLayer = window.viewer.dataSources.getByName('highLightLayer')[0]
      if (!highLightLayer) {
        highLightLayer = new Cesium.CustomDataSource('highLightLayer')
        window.viewer.dataSources.add(highLightLayer)
      }
      // 绘制
      highLightLayer.entities.removeAll()
    }
  },
  watch: {
    type() {
      if (this.type.endsWith('POINT')) {  // 点
        this.list = [
          {type: 'string', name: '物探点号'},
          {type: 'number', name: '地面高程'},
          {type: 'number', name: '井深'},
          {type: 'string', name: '特征'},
          {type: 'string', name: '附属物'},
        ]

      } else { // 线
        this.list = [
          {type: 'string', name: '起点点号'},
          {type: 'string', name: '终点点号'},
          {type: 'number', name: '起点埋深'},
          {type: 'number', name: '终点埋深'},
          {type: 'number', name: '起点高程'},
          {type: 'number', name: '终点高程'},
          {type: 'string', name: '埋设方式'},
          {type: 'number', name: '管径'},
          {type: 'string', name: '材质'},
          {type: 'string', name: '所在道路'},
        ]
      }
    }
  },
  computed: {},
  beforeDestroy() {
    clearWindow()
    this.clearDraw()
  },
}
</script>

<style scoped>
.main-pointGroupSearch {
  position: relative;
  height: 100%;
  width: 100%;
  padding: 0 10px
}

.listPanel {
  height: 70%;
  width: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  border-bottom: none !important;
}

.listTopPanel {
  height: 40px;
  margin: 0 !important;
}

.listBottomPanel {
  display: flex;
  justify-content: space-between;
  height: calc(100% - 40px);
  padding-right: 100px
}

.listBottomPanel > * {
  height: 100% !important;
  display: flex;
  flex-direction: column;
}

.sqlPanel {
  width: 100%;
  height: 25%;
  margin-top: 10px;
  resize: none;
  border-radius: 3px;
  background-color: transparent;
  color: white;
  line-height: 24px;
  border-color: rgba(0, 191, 255, 0.5);
  padding: 5px;
}

.buttonGroup {
  display: flex;
  flex-direction: column;
  width: 70px;
  justify-content: space-between;

}

.buttonGroup > button {
  height: 13%;
  line-height: 20px;
  color: white !important;
  border: none;
}

.listBottomPanel > ul {
  line-height: 20px;
  overflow-y: scroll;
  padding: 5px !important;
  border-radius: 3px;
  box-shadow: 0 0 5px rgba(0, 0, 0, 0.1) inset;
}

ul li {
  cursor: pointer;
}

.active {
  background-color: rgba(0, 191, 255, 0.1);
}
</style>
<style scoped>
::-webkit-scrollbar {
  width: 5px;
  height: 5px;
  background-color: transparent;
}

/* 定义滚动条轨道的样式 */
::-webkit-scrollbar-track {
  -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.0);
  border-radius: 10px;
  background-color: transparent;
}

/* 定义滚动条滑块的样式 */
::-webkit-scrollbar-thumb {
  border-radius: 10px;
  -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, .0);
  background-color: rgba(0, 191, 255, 0.5);
}
</style>
